package com.ebt.m.wiki;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewStub;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebt.m.AppLog;
import com.ebt.m.R;
import com.ebt.m.data.entity.ProductBridgeObj;
import com.ebt.m.fragment.LazyFragment;
import com.ebt.m.utils.MathUtil;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.view.AgeSeekBar;
import com.ebt.m.widget.indemnify.IndemnifyConfig;
import com.ebt.m.widget.indemnify.chart.EbtIndemnifyA;
import com.ebt.m.widget.tablescroll.scroll.AdapterBenefitList;
import com.ebt.m.widget.tablescroll.scroll.RecycleAdapterBenefitList2;
import com.ebt.m.widget.tablescroll.scroll.RecycleViewDivider;
import com.ebt.m.widget.tablescroll.scroll.RowBenefit;
import com.ebt.m.wiki.bean.AreaChartConfig;
import com.ebt.m.wiki.event.EOnCalculatorChange;
import com.ebt.m.wiki.view.ProductSingAgeItem;
import com.tendcloud.tenddata.TCAgent;

import org.achartengine.chart.PointStyle;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author
 * @description 产品-利益图表
 */
public class FrgProductTable2 extends LazyFragment implements View.OnClickListener {
    public static final String FLAG_DATA = "data";
    public static final int VISIBLE = View.VISIBLE;
    public static final int INVISIBLE = View.INVISIBLE;
    public static final int GONE = View.GONE;
    private Context mContext;

    private RelativeLayout indemnifyALayout;
    private LinearLayout ll_custom_module;
    private LinearLayout age__ll_container;
    /* 客户信息-e */
    private AgeSeekBar ageSeekBar;
    /* 计算条件-s */
    private View mainView;
    private EbtIndemnifyA ebtIndemnifyA;
    // ----------------view-----------------------
    /**
     * 利益图原始数据
     */
    private List<AreaChartConfig> areaChartConfigList;
    /**
     * 面积图绘制参数
     */
    private IndemnifyConfig mIndemnifyConfig;
    private IndemnifyConfig mSingleAgeConfig;


    private ProductBridgeObj mProductObj;
    private double width;
    private int seekBarMaxInterval = 120;
    private int seekBarMinAge = 0;
    /*表格*/
    private RelativeLayout rl_tablehead;
    private RecyclerView listView;
    private LinearLayout ll_benifit_titles;
    private ArrayList<RowBenefit> rowBenefitDatas = new ArrayList<>();
    private RecycleAdapterBenefitList2 adapter;
    private TextView tvRowAge;

    private View tableContainer;
    private View chartContainer;
    private View ageContainer;
    private RadioGroup tableRg;
    private View minusView;
    private View plusView;


    public static FrgProductTable2 newInstance(Boolean allowShowTab) {
        FrgProductTable2 frg = new FrgProductTable2();
        Bundle bundle = new Bundle();
        bundle.putBoolean("allowShowTab", allowShowTab);
        frg.setArguments(bundle);
        return frg;
    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        super.onCreateViewLazy(savedInstanceState);
        mainView = inflater.inflate(R.layout.wiki_frg_product_table_coordinate2, null);
        mContext = inflater.getContext();
        Bundle bundle = getArguments();
        boolean allowShowTab = bundle.getBoolean("allowShowTab",true);
        if (!allowShowTab) {
            onDataSyncPost();
            return;
        }
        mIndemnifyConfig = new IndemnifyConfig();
        mSingleAgeConfig = new IndemnifyConfig();
        areaChartConfigList = new ArrayList<AreaChartConfig>();
        EventBus.getDefault().register(this);
        initView();
        setContentView(mainView);
        onDataSyncPost();
    }



    /**
     * 初始化view
     */
    private void initView() {
        tableRg = (RadioGroup) findViewById(R.id.rg_table);
        RadioButton rb_all = (RadioButton) tableRg.findViewById(R.id.rd_all);
        rb_all.setChecked(true);
        switchContent(0);
        tableRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int position = 0;
                switch (checkedId) {
                    case R.id.rd_all:
                        position = 0;
                        break;
                    case R.id.rd_age:
                        position = 1;
                        break;
                    case R.id.rd_chart:
                        position = 2;
                        break;
                }
                switchContent(position);
                String[] labels = {"全部", "分龄", "图表"};
                TCAgent.onEvent(mContext, "chart_table_subtab", labels[position]);
            }
        });

    }

    private void switchContent(int position) {
        if (position == 0) {
            if (chartContainer == null) {
                ViewStub chartVb = (ViewStub) findViewById(R.id.vs_chart);
                chartContainer = chartVb.inflate();
                indemnifyALayout = (RelativeLayout) chartContainer.findViewById(R.id.indemnifyALayout);
                ll_custom_module = (LinearLayout) chartContainer.findViewById(R.id.ll_custom_module);
            } else {
                chartContainer.setVisibility(View.VISIBLE);
            }
            if ((tableContainer != null)) {
                tableContainer.setVisibility(View.GONE);
            }
            if (ageContainer != null) {
                ageContainer.setVisibility(View.GONE);
            }
        } else if (position == 1) {
            if (ageContainer == null) {
                ViewStub chartVb = (ViewStub) findViewById(R.id.vs_age);
                ageContainer = chartVb.inflate();
                ageSeekBar = (AgeSeekBar) ageContainer.findViewById(R.id.age_seekbar);
                ageSeekBar.setThumbDrawable(R.drawable.ic_age_seekbar);
                minusView = ageContainer.findViewById(R.id.minus);
                plusView = ageContainer.findViewById(R.id.plus);
                age__ll_container = (LinearLayout) ageContainer.findViewById(R.id.age__ll_container);
                initAgeData();
            } else {
                ageContainer.setVisibility(View.VISIBLE);
            }
            if ((chartContainer != null)) {
                chartContainer.setVisibility(View.GONE);
            }
            if (tableContainer != null) {
                tableContainer.setVisibility(View.GONE);
            }
        } else if (position == 2) {
            if (tableContainer == null) {
                ViewStub chartVb = (ViewStub) findViewById(R.id.vs_table);
                tableContainer = chartVb.inflate();
                initTableView(tableContainer);
            } else {
                tableContainer.setVisibility(View.VISIBLE);
            }
            if ((chartContainer != null)) {
                chartContainer.setVisibility(View.GONE);
            }
            if (ageContainer != null) {
                ageContainer.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 当被保人属性改变时，初始化SeekBar,并且默认显示全部年龄利益
     */
    private void initSeekBarOnInsuredPersonChanged() {
        plusView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((ageSeekBar.getProgress() + 1) <= seekBarMaxInterval) {
                    ageSeekBar.setProgress(ageSeekBar.getProgress() + 1);
                    refreshAllAreaBenefitChart(true);
                }
            }
        });
        minusView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((ageSeekBar.getProgress() - 1) >= 0) {
                    ageSeekBar.setProgress(ageSeekBar.getProgress() - 1);
                    refreshAllAreaBenefitChart(true);
                }
            }
        });
        ageSeekBar.setOnProgressChangedLisnter(new AgeSeekBar.OnProgressChangedListner() {
            @Override
            public void onProgressChanged(int progress) {

                refreshAllAreaBenefitChart(true);
            }
        });
        //设置seekbar的最新范围，并默认为最大。
        List<AreaChartConfig> listAll = mProductObj.getAreaChartConfigList();
        if (listAll != null && listAll.size() > 0) {
            AreaChartConfig areaChartConfig = listAll.get(0);
            int[] xArray = areaChartConfig.getxIntArray();
            int xMinInt = MathUtil.getMinValueOfIntArray(xArray);
            int xMaxInt = MathUtil.getMaxValueOfIntArray(xArray);
            seekBarMinAge = xMinInt;
            seekBarMaxInterval = xMaxInt - seekBarMinAge;
        }
        //单选时设置最大值
        ageSeekBar.setMaxProgress(seekBarMaxInterval, seekBarMinAge);
        //获取到宽度和高度后，可用于计算
        //设置seekbar为最大值
        ageSeekBar.setProgress(seekBarMaxInterval);
    }

    /**
     * 刷新面积图利益图表
     */
    protected void refreshAllAreaBenefitChart(boolean isSingle) {
        if (isSingle) {
            if (ageContainer == null) {
                return;
            }
            mSingleAgeConfig.setSingle(true);
            setIndemnifyConfig(areaChartConfigList, mSingleAgeConfig, true);
            setSingleAreaChartRange();
            setAgeContainer();
        } else {
            mIndemnifyConfig.setSingle(false);
            setIndemnifyConfig(areaChartConfigList, mIndemnifyConfig, false);
            setSingleAreaChartRange();
            drawAreaChart(indemnifyALayout);
        }
    }

    private void setAgeContainer() {
        if (age__ll_container == null) {
            return;
        }
        int[] maxValues = mSingleAgeConfig.getMinMaxValue(mContext.getResources().getDimension(R.dimen.product_age_item));
        int maxValue = maxValues[1];
        int maxTitleValue = maxValues[0];
        if (age__ll_container.getChildCount() < 1) {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 60);
            layoutParams.setMargins(0, 5, 0, 5);
            for (int i = 0; i < areaChartConfigList.size(); i++) {
                ProductSingAgeItem ageItem = new ProductSingAgeItem(getContext());
                age__ll_container.addView(ageItem, layoutParams);

            }
        }
        for (int i = 0; i < age__ll_container.getChildCount(); i++) {
            View child = age__ll_container.getChildAt(i);
            if (child instanceof ProductSingAgeItem) {
                double[] yValues = (double[]) mSingleAgeConfig.getXyVaules()[i][1];
                ProductSingAgeItem ageItem = ((ProductSingAgeItem) child);
                ageItem.update(mSingleAgeConfig.getTitles()[maxTitleValue], maxValue, yValues[0], mSingleAgeConfig.getColors()[i], mSingleAgeConfig.getTitles()[i]);
            }
        }
    }

    /**
     * 根据图例颜色生成对应的selector
     */
    protected StateListDrawable createLengendSelector(int color) {

        Drawable defaultDrawable = getDrawableByColor(color, false);
        Drawable checkedDrawable = getDrawableByColor(color, true);

        StateListDrawable sld = new StateListDrawable();
        sld.addState(new int[]{-android.R.attr.state_focused, -android.R.attr.state_pressed, -android.R.attr.state_checked},
                defaultDrawable);
        sld.addState(new int[]{-android.R.attr.state_focused, -android.R.attr.state_pressed, android.R.attr.state_checked},
                checkedDrawable);
        return sld;
    }

    private Paint paint;

    /**
     * 根据颜色，绘制对应的图例
     *
     * @param color
     * @param checked
     * @return
     */
    protected Drawable getDrawableByColor(int color, boolean checked) {
        // 默认位图配置
        Bitmap.Config CONFIG = Bitmap.Config.RGB_565;

        int size = UIHelper.dip2px(mContext, 18);
        int sizeInner = size * 4 / 5;
        int offet = size / 10;
        int center = size / 2;

        Bitmap resBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_checkbox_check);

        Bitmap bmp = Bitmap.createBitmap(size, size, CONFIG);
        Canvas canvas = new Canvas(bmp);

        if (paint == null) {
            paint = new Paint();
            paint.setAntiAlias(true);
        }

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.WHITE);
        canvas.drawRect(new Rect(0, 0, size, size), paint);

        paint.setColor(color);
        canvas.drawRoundRect(new RectF(0, 0, size, size), 10, 10, paint);

        if (checked) {
            paint.setStyle(Paint.Style.STROKE);
            canvas.drawBitmap(resBitmap, new Rect(0, 0, resBitmap.getWidth(), resBitmap.getHeight()), new RectF(offet, offet, offet + sizeInner, offet + sizeInner), paint);
        }

        return new BitmapDrawable(mContext.getResources(), bmp);
    }

    private void setChart() {
        ll_custom_module.removeAllViews();
        areaChartConfigList.clear();
        if (mProductObj != null) {
            areaChartConfigList.addAll(mProductObj.getAreaChartConfigList());
//            ViewGroupAutoLines myViewGroup = new ViewGroupAutoLines(getContext());
            for (int i = 0, size = areaChartConfigList.size(); i < size; i++) {
                AreaChartConfig module = areaChartConfigList.get(i);
                CheckBox cb = new CheckBox(mContext);
                cb.setButtonDrawable(createLengendSelector(Color.parseColor(module.getFillColor())));
                cb.setChecked(true);
                cb.setOnCheckedChangeListener(onCheckedChangeListener);
                cb.setTag(i);
                cb.setLineSpacing(0f, 1.2f);
                cb.setText(getAreaChartDescription(module));
                cb.setPadding(10, 10, 10, 10);
                cb.setTextSize(14);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(40, 5, 40, 5);
                cb.setLayoutParams(layoutParams);
                ll_custom_module.addView(cb);
            }
        }
    }

    CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int index = (int) buttonView.getTag();
            AreaChartConfig areaChartConfig = areaChartConfigList.get(index);
            areaChartConfig.setShow(isChecked);
            //刷新面积图
            refreshAllAreaBenefitChart(false);
            if (isChecked) {
                TCAgent.onEvent(mContext, "chart_legend_click", areaChartConfig.getTitle());
            }
        }
    };

    private SpannableString getAreaChartDescription(AreaChartConfig chartConfig) {
        String title = chartConfig.getTitle();
        String description = chartConfig.getDescription();
        String priceStr = "";
        if (description.contains("[") && description.contains("]")) {
            priceStr = description.substring(description.indexOf("[") + 1, description.lastIndexOf("]"));
        } else {
            priceStr = description;
        }
        String allStr = title + ":" + priceStr;
        SpannableString stringBuilder = new SpannableString(allStr);
        stringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#B76073")), title.length() + 1, allStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return stringBuilder;

    }

    /**
     * @param data
     * @Description: 配置利益图参数
     * @throw
     */
    private void setIndemnifyConfig(List<AreaChartConfig> data, IndemnifyConfig config, boolean isSingle) {
        int size = data.size();
        String[] sounds = new String[size];
        String[] descs = new String[size];
        final String[] titles = new String[size];
        int[] colors = new int[size];
        int[] shapeTypes = new int[size];
        PointStyle[] pointStyles = new PointStyle[size];
        boolean[] isShow = new boolean[size];

        for (int i = 0; i < size; i++) {
            isShow[i] = true;
        }
        for (int i = 0; i < pointStyles.length; i++) {
            pointStyles[i] = PointStyle.CIRCLE;
        }
        // 点坐标
        Object[][] xyVaules = new Object[size][2];

        int index = 0;
        double[] xAge;
        double[] yValue;
        for (AreaChartConfig eEBTAreaData : data) {

            sounds[index] = eEBTAreaData.getRecordFile();
            // 描述
            descs[index] = eEBTAreaData.getDescription();
            // 标题
            titles[index] = eEBTAreaData.getTitle();
            // 颜色
            colors[index] = Color.parseColor("#" + "AA" + eEBTAreaData.getFillColor().replace("#", ""));
            shapeTypes[index] = eEBTAreaData.getChartType();
            // 横轴坐标
            int[] xs = eEBTAreaData.getxIntArray();
            // 纵轴坐标
            Object[] ys = eEBTAreaData.getyDoubleArray();
            if (isSingle) {
                xAge = new double[1];
                yValue = new double[1];
                for (int i = 0; i < xs.length; i++) {
                    if (xs[i] == ageSeekBar.getSelectedAge())//当前选中年龄
                    {
                        xAge[0] = (double) xs[i];
                        yValue[0] = MathUtil.getTwoDecimalDouble(((double[]) ys[i])[1]);
                        break;
                    }
                }

            } else {
                xAge = new double[xs.length];
                // 纵轴坐标
                yValue = new double[ys.length];
                for (int i = 0; i < xAge.length; i++) {
                    xAge[i] = (double) xs[i];
                    yValue[i] = MathUtil.getTwoDecimalDouble(((double[]) ys[i])[1]);
                }
            }
            // 点坐标
            xyVaules[index][0] = xAge;
            xyVaules[index][1] = yValue;
            index++;
        }

        config.setIsShow(isShow);
        config.setSounds(sounds);// 配置声音
        config.setDescs(descs);// 配置描述
        config.setXYVaules(xyVaules);// 配置横纵轴数据
        config.setTitles(titles);// 配置标题数组
        config.setColors(colors);// 配置颜色数组
        config.setShapeTypes(shapeTypes);// 形状类型 0-面积形 1-线形 2-柱形
        config.setPointStyles(pointStyles);

        config.setAxesColor(Color.BLACK);// 横纵轴颜色
        config.setLabelsColor(Color.BLACK);// 标题及横纵轴标记文字颜色
        config.setMarginsColor(Color.rgb(255, 255, 255));// 边框颜色
    }

    /**
     * 设置单个利益图的范围
     */
    private void setSingleAreaChartRange() {
        if (areaChartConfigList.size() > 0) {
            AreaChartConfig eEBTAreaData = areaChartConfigList.get(0);
            setXRanges(eEBTAreaData);
        }
    }

    /**
     * 设置横坐标范围
     *
     * @param eEBTAreaData
     * @param eEBTAreaData x坐标间隔
     */
    private void setXRanges(AreaChartConfig eEBTAreaData) {
        // 横轴坐标
        int[] xs = eEBTAreaData.getxIntArray();
        int xMinInt = MathUtil.getMinValueOfIntArray(xs);
        int xMaxInt = MathUtil.getMaxValueOfIntArray(xs);
        AppLog.debug("xMinInt is " + xMinInt);
        AppLog.debug("xMaxInt is " + xMaxInt);
        int interval = 1;//默认为1
        int xInitialMinAge = 0;
        //设定刻度数固定为23个。间隔为22个。重新计算刻度开始值和最小间隔。
        int xRangeInterval = xMaxInt - xMinInt;
        int calMinInterval = xRangeInterval / 22;
        if (xRangeInterval % 22 >= 0) {
            calMinInterval++;
        }
        interval = calMinInterval;
        mIndemnifyConfig.setIntervalAge(interval);
        xInitialMinAge = xMinInt - interval;

        int xCount = EbtIndemnifyA.XLabels;
        if (xInitialMinAge < 0) {
            xInitialMinAge += interval;
        }
        int xInitialMaxAge = xInitialMinAge + interval * xCount;
//        if (xInitialMaxAge > xMaxInt) {
//            xInitialMaxAge = xMaxInt + 1;
//        }
        // 计算最大范围
        double xRangeMinDouble = xInitialMinAge;
        double xRangeMaxDouble = xInitialMaxAge;
        mIndemnifyConfig.setxInitialMinAge(xInitialMinAge);
        mIndemnifyConfig.setxInitialMaxAge(xInitialMaxAge);
        mIndemnifyConfig.setxRangeMinDouble(xRangeMinDouble);
        mIndemnifyConfig.setxRangeMaxDouble(xRangeMaxDouble);
    }

    /**
     * 创建面积图图形
     *
     * @param indemnifyALayout
     */
    private void drawAreaChart(RelativeLayout indemnifyALayout) {
        int size = areaChartConfigList.size();
        if (size > 0) {
            boolean[] isShow = new boolean[size];
            for (int i = 0; i < size; i++) {
                AreaChartConfig areaChart = areaChartConfigList.get(i);
                isShow[i] = areaChart.isShow();
            }

            mIndemnifyConfig.setIsShow(isShow);
            ebtIndemnifyA = new EbtIndemnifyA(mContext, mIndemnifyConfig);
            indemnifyALayout.removeAllViews();
            mIndemnifyConfig.setxTitle(IndemnifyConfig.X_TITLE_AGE);
            ebtIndemnifyA.setShapeType(EbtIndemnifyA.SHAPE_AREA_DEFAULT);
            indemnifyALayout.addView(ebtIndemnifyA.getView());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }


    private void initChartData() {
        ll_custom_module.post(new Runnable() {
            @Override
            public void run() {
                setChart();
                refreshAllAreaBenefitChart(false);
            }
        });

    }

    private void initAgeData() {
        if (ageContainer != null) {
            ageContainer.post(new Runnable() {
                @Override
                public void run() {
                    initSeekBarOnInsuredPersonChanged();
                    refreshAllAreaBenefitChart(true);
                }
            });
        }
    }

    private void initTableView(View tableContainer) {
        rowBenefitDatas.clear();
        listView = (RecyclerView) tableContainer.findViewById(R.id.lvTableBenifits);
        ll_benifit_titles = (LinearLayout) tableContainer.findViewById(R.id.ll_benifit_titles);
        rl_tablehead = (RelativeLayout) tableContainer.findViewById(R.id.rl_tablehead);
        tvRowAge = (TextView) (rl_tablehead.findViewById(R.id.tvRowAge));
        tvRowAge.setText("年龄");
        rl_tablehead.setOnTouchListener(new ListViewAndHeadViewTouchListener());
        listView.setOnTouchListener(new ListViewAndHeadViewTouchListener());
        initTableViewData();
        adapter = new RecycleAdapterBenefitList2(getContext(), rowBenefitDatas, rl_tablehead);
        listView.setLayoutManager(new LinearLayoutManager(getContext()));
        listView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, UIHelper.dip2px(mContext, 0.5f), mContext.getResources().getColor(R.color.table_column_divler), false));
        listView.setAdapter(adapter);
    }

    public void initTableViewData() {
        ll_benifit_titles.removeAllViews();
        List<AreaChartConfig> listAll = mProductObj.getAreaChartConfigList();
        //初始化利益名称列名
        for (int i = 0, size = listAll.size(); i < size; i++) {
            AreaChartConfig module = listAll.get(i);
            TextView textView = new TextView(getContext());
            textView.setGravity(Gravity.CENTER);
            textView.setWidth(UIHelper.dip2px(getContext(), AdapterBenefitList.tablecellwidth));
            textView.setHeight(UIHelper.dip2px(getContext(), AdapterBenefitList.tablecellheight));
            textView.setTextSize(AdapterBenefitList.tablecelltextsize);
            textView.setTextColor(mContext.getResources().getColor(R.color.table_header_textcolor_modify));
            textView.setText(module.getTitle());
            ll_benifit_titles.addView(textView);
            /** 添加垂直分隔线 **/
            if (i < size - 1) {
                TextView divlerView = new TextView(getContext());
                divlerView.setWidth(UIHelper.dip2px(getContext(), 0.5f));
                divlerView.setHeight(UIHelper.dip2px(getContext(), AdapterBenefitList.tablecellheight));
                divlerView.setBackgroundColor(getContext().getResources().getColor(R.color.table_column_divler));
                ll_benifit_titles.addView(divlerView);
            }
        }
        //获取行数
        RowBenefit rowBenefit;
        List<Double> benefits;
        //取年龄值
        AreaChartConfig eEBTAreaData = getMaxInsuredAgeItem(listAll);
        // 横轴坐标
        if (eEBTAreaData != null) {
            int[] xs = eEBTAreaData.getxIntArray();
            double yValue;
            Object[] ys;
            for (int j = 0; j < xs.length; j++) {
                rowBenefit = new RowBenefit();
                rowBenefit.setAge(xs[j]);
                benefits = new ArrayList<Double>();
                for (int i = 0, size = listAll.size(); i < size; i++) {
                    // 纵轴坐标
                    eEBTAreaData = listAll.get(i);
                    ys = eEBTAreaData.getyDoubleArray();
                    if (ys.length > j) {
                        yValue = MathUtil.getTwoDecimalDouble(((double[]) ys[j])[1]);
                    } else {
                        yValue = 0;
                    }
                    benefits.add(yValue);
                }
                rowBenefit.setBenefitsPerAge(benefits);
                rowBenefitDatas.add(rowBenefit);
            }
        }

    }

    private AreaChartConfig getMaxInsuredAgeItem(List<AreaChartConfig> listAll) {
        if (listAll.size() <= 0) {
            return null;
        }
        List<AreaChartConfig> newList = new ArrayList<>(listAll);
        Collections.sort(newList, new Comparator<AreaChartConfig>() {
            @Override
            public int compare(AreaChartConfig o1, AreaChartConfig o2) {
                return o1.getMaxInsuredAge() - o2.getMaxInsuredAge();
            }
        });
        return newList.get(newList.size() - 1);
    }

    class ListViewAndHeadViewTouchListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            HorizontalScrollView headScrollView = (HorizontalScrollView) rl_tablehead
                    .findViewById(R.id.hsrollviewTable);
            headScrollView.onTouchEvent(arg1);
            return false;
        }
    }


    @Override
    public Context getContext() {
        return mContext;
    }

    @Override
    public View findViewById(int wikiTab2Tabcontent) {
        return mainView.findViewById(wikiTab2Tabcontent);
    }

    @Override
    protected void onDataSyncStart() {
        super.onDataSyncStart();
        initChartData();
    }

    /**
     * 设置所需参数
     *
     * @param mProductObj
     */
    public void setmProductObj(ProductBridgeObj mProductObj) {
        this.mProductObj = mProductObj;
    }

    /****************************************
     * Event
     ****************************************/
    @Subscribe
    public void onEvent(EOnCalculatorChange epc) {
        this.mProductObj = epc.mProductObj;
        //初始化之后才更新
        if (mainView != null) {
            if (epc != null && epc.isChanged) {
                this.mProductObj = epc.mProductObj;
                setChart();
                refreshAllAreaBenefitChart(false);
                initAgeData();
                if (tableContainer != null) {
                    initTableView(tableContainer);
                }
            }
        }
    }

    @Override
    protected void onDestroyViewLazy() {
        super.onDestroyViewLazy();
        EventBus.getDefault().unregister(this);
    }
}
